<template>
  <el-dialog
    v-model="visible"
    :title="t('dashboard.vipCenter.upgradeDialog.title')"
    width="700px"
    :before-close="handleClose"
    class="vip-upgrade-dialog"
    :class="{ 'dark': isDark }"
  >
    <div class="upgrade-content">
      <!-- 当前状态展示 -->
      <div v-if="isVip" class="current-status">
        <el-alert
          :title="t('dashboard.vipCenter.upgradeDialog.currentStatus', { userType, daysLeft: formatDaysLeft(daysLeft) })"
          type="success"
          :closable="false"
          show-icon
        />
      </div>

      <!-- 套餐选择 -->
      <div class="plans-container">
        <h3 class="section-title">{{ t('dashboard.vipCenter.upgradeDialog.selectPlan') }}</h3>
        <div class="plans-grid">
          <div
            v-for="(plan, key) in VIP_PLANS"
            :key="key"
            class="plan-card"
            :class="{ 
              'selected': selectedPlan === key,
              'popular': plan.popular 
            }"
            @click="selectPlan(key)"
          >
            <!-- 热门标签 -->
            <div v-if="plan.popular" class="popular-badge">
              <el-tag type="warning" size="small">{{ t('dashboard.vipCenter.upgradeDialog.mostPopular') }}</el-tag>
            </div>

            <!-- 套餐标题 -->
            <div class="plan-header">
              <h4 class="plan-name">{{ plan.name }}</h4>
              <div v-if="plan.discount" class="discount-tag">
                {{ plan.discount }}
              </div>
            </div>

            <!-- 价格展示 -->
            <div class="plan-price">
              <div class="current-price">
                <span class="price-symbol">{{ t('dashboard.vipCenter.upgradeDialog.priceSymbol') }}</span>
                <span class="price-amount">{{ plan.price.toFixed(2) }}</span>
                <span class="price-period">/ {{ plan.period }}</span>
              </div>
              <div v-if="plan.originalPrice !== plan.price" class="original-price">
                {{ t('dashboard.vipCenter.upgradeDialog.originalPrice', { price: plan.originalPrice.toFixed(2) }) }}
              </div>
            </div>

            <!-- 功能列表 -->
            <div class="plan-features">
              <div
                v-for="feature in plan.features"
                :key="feature"
                class="feature-item"
              >
                <el-icon class="feature-icon"><Check /></el-icon>
                <span>{{ feature }}</span>
              </div>
            </div>

            <!-- 选择按钮 -->
            <div class="plan-action">
              <el-button
                :type="selectedPlan === key ? 'primary' : 'default'"
                :class="{ 'selected-btn': selectedPlan === key }"
                @click.stop="selectPlan(key)"
              >
                {{ selectedPlan === key ? t('dashboard.vipCenter.upgradeDialog.selected') : t('dashboard.vipCenter.upgradeDialog.selectPlan') }}
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 支付方式选择 -->
      <div v-if="selectedPlan" class="payment-methods">
        <h3 class="section-title">{{ t('dashboard.vipCenter.upgradeDialog.paymentMethods') }}</h3>
        <el-radio-group v-model="selectedPaymentMethod" class="payment-options">
          <el-radio label="ALIPAY" class="payment-option">
            <div class="payment-info">
              <img src="/icons/alipay.png" :alt="t('dashboard.vipCenter.upgradeDialog.alipay')" class="payment-icon" />
              <span>{{ t('dashboard.vipCenter.upgradeDialog.alipay') }}</span>
            </div>
          </el-radio>
          <!-- 可以添加更多支付方式 -->
          <!-- <el-radio label="WECHAT" class="payment-option">
            <div class="payment-info">
              <img src="/icons/wechat.png" alt="微信支付" class="payment-icon" />
              <span>微信支付</span>
            </div>
          </el-radio> -->
        </el-radio-group>
      </div>

      <!-- 订单摘要 -->
      <div v-if="selectedPlan" class="order-summary">
        <h3 class="section-title">{{ t('dashboard.vipCenter.upgradeDialog.orderSummary') }}</h3>
        <div class="summary-content">
          <div class="summary-row">
            <span>{{ t('dashboard.vipCenter.upgradeDialog.planLabel') }}</span>
            <span>{{ VIP_PLANS[selectedPlan].name }}</span>
          </div>
          <div class="summary-row">
            <span>{{ t('dashboard.vipCenter.upgradeDialog.durationLabel') }}</span>
            <span>{{ VIP_PLANS[selectedPlan].period === '月' ? t('dashboard.vipCenter.upgradeDialog.oneMonth') : t('dashboard.vipCenter.upgradeDialog.oneYear') }}</span>
          </div>
          <div v-if="VIP_PLANS[selectedPlan].originalPrice !== VIP_PLANS[selectedPlan].price" class="summary-row discount-row">
            <span>{{ t('dashboard.vipCenter.upgradeDialog.originalPriceLabel') }}</span>
            <span>{{ t('dashboard.vipCenter.upgradeDialog.priceSymbol') }}{{ VIP_PLANS[selectedPlan].originalPrice.toFixed(2) }}</span>
          </div>
          <div v-if="VIP_PLANS[selectedPlan].originalPrice !== VIP_PLANS[selectedPlan].price" class="summary-row discount-row">
            <span>{{ t('dashboard.vipCenter.upgradeDialog.discountLabel') }}</span>
            <span class="discount-amount">-{{ t('dashboard.vipCenter.upgradeDialog.priceSymbol') }}{{ (VIP_PLANS[selectedPlan].originalPrice - VIP_PLANS[selectedPlan].price).toFixed(2) }}</span>
          </div>
          <div class="summary-row total-row">
            <span>{{ t('dashboard.vipCenter.upgradeDialog.totalAmountLabel') }}</span>
            <span class="total-amount">{{ t('dashboard.vipCenter.upgradeDialog.priceSymbol') }}{{ VIP_PLANS[selectedPlan].price.toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ t('dashboard.vipCenter.upgradeDialog.cancel') }}</el-button>
        <el-button
          type="primary"
          :loading="paymentLoading"
          :disabled="!selectedPlan || !selectedPaymentMethod"
          @click="handlePayment"
          class="pay-button"
        >
          {{ paymentLoading ? t('dashboard.vipCenter.upgradeDialog.processing') : t('dashboard.vipCenter.upgradeDialog.payNow', { amount: selectedPlan ? VIP_PLANS[selectedPlan].price.toFixed(2) : '0.00' }) }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import { useVipStore, VIP_PLANS } from '@/stores/vip'
import { useThemeStore } from '@/stores/theme'

const router = useRouter()
const { t } = useI18n()
const vipStore = useVipStore()
const themeStore = useThemeStore()

// 响应式数据
const selectedPlan = ref<string>('')
const selectedPaymentMethod = ref<string>('ALIPAY')
const paymentLoading = ref(false)

// 计算属性
const visible = computed({
  get: () => vipStore.upgradeDialogVisible,
  set: (value: boolean) => {
    if (!value) {
      vipStore.hideUpgradeDialog()
    }
  }
})

const isVip = computed(() => vipStore.isVip)
const userType = computed(() => vipStore.userType)
const daysLeft = computed(() => vipStore.daysLeft)
const isDark = computed(() => themeStore.isDark)

// 方法
const selectPlan = (planKey: string) => {
  selectedPlan.value = planKey
}

const handleClose = () => {
  vipStore.hideUpgradeDialog()
  // 重置选择
  selectedPlan.value = ''
  selectedPaymentMethod.value = 'ALIPAY'
}

const formatDaysLeft = (days: number) => {
  return vipStore.formatDaysLeft(days)
}

const handlePayment = async () => {
  if (!selectedPlan.value) {
    ElMessage.warning(t('dashboard.vipCenter.upgradeDialog.selectPlanFirst'))
    return
  }

  paymentLoading.value = true

  try {
    // 创建支付订单
    const order = await vipStore.createPaymentOrder(selectedPlan.value)
    
    // 创建支付宝支付
    const paymentHtml = await vipStore.createAlipayPayment(order.orderNo)
    
    // 处理支付宝返回的HTML表单
    if (paymentHtml) {
      // Electron环境：使用路由跳转到专门的支付页面
      // 将支付HTML存储到sessionStorage，避免URL参数问题
      sessionStorage.setItem('vipPaymentHtml', paymentHtml)
      sessionStorage.setItem('vipOrderNo', order.orderNo)
      
      ElMessage.success(t('dashboard.vipCenter.upgradeDialog.redirectingToPayment'))
      handleClose()
      
      // 跳转到支付页面
      router.push('/vip-payment')
      
    } else {
      throw new Error(t('dashboard.vipCenter.upgradeDialog.getPaymentInfoFailed'))
    }
    
  } catch (error: any) {
    console.error('支付失败:', error)
    ElMessage.error(error.message || t('dashboard.vipCenter.upgradeDialog.paymentFailed'))
  } finally {
    paymentLoading.value = false
  }
}
</script>

<style scoped>
.vip-upgrade-dialog {
  border-radius: 12px;
}

.vip-upgrade-dialog.dark :deep(.el-dialog) {
  background: #1e293b;
}

.vip-upgrade-dialog.dark :deep(.el-dialog__header) {
  background: #0f172a;
  border-bottom: 1px solid #334155;
}

.vip-upgrade-dialog.dark :deep(.el-dialog__title) {
  color: #f1f5f9;
}

.vip-upgrade-dialog.dark :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #94a3b8;
}

.vip-upgrade-dialog.dark :deep(.el-dialog__body) {
  background: #1e293b;
}

.vip-upgrade-dialog.dark :deep(.el-dialog__footer) {
  background: #1e293b;
  border-top: 1px solid #334155;
}

.upgrade-content {
  padding: 10px 0;
}

.current-status {
  margin-bottom: 20px;
}

.section-title {
  margin: 20px 0 15px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  transition: color 0.2s ease;
}

.vip-upgrade-dialog.dark .section-title {
  color: #f1f5f9;
}

.plans-container {
  margin-bottom: 25px;
}

.plans-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.plan-card {
  position: relative;
  border: 2px solid #e4e7ed;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff;
}

.vip-upgrade-dialog.dark .plan-card {
  background: #0f172a;
  border-color: #334155;
}

.plan-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.vip-upgrade-dialog.dark .plan-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.25);
}

.plan-card.selected {
  border-color: #409eff;
  background: var(--el-color-primary-light-9);
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.2);
}

.vip-upgrade-dialog.dark .plan-card.selected {
  background: #1e3a8a;
  border-color: #409eff;
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.3);
}

.plan-card.popular {
  border-color: #f39c12;
}

.plan-card.popular.selected {
  background: var(--el-color-warning-light-9);
  box-shadow: 0 4px 20px rgba(243, 156, 18, 0.2);
}

.vip-upgrade-dialog.dark .plan-card.popular.selected {
  background: #92400e;
  box-shadow: 0 4px 20px rgba(243, 156, 18, 0.3);
}

.popular-badge {
  position: absolute;
  top: -10px;
  right: 15px;
}

.plan-header {
  text-align: center;
  margin-bottom: 15px;
}

.plan-name {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 5px 0;
  color: #303133;
  transition: color 0.2s ease;
}

.vip-upgrade-dialog.dark .plan-name {
  color: #f1f5f9;
}

.discount-tag {
  color: #f39c12;
  font-size: 12px;
  font-weight: 500;
}

.plan-price {
  text-align: center;
  margin-bottom: 20px;
}

.current-price {
  display: flex;
  align-items: baseline;
  justify-content: center;
  gap: 2px;
}

.price-symbol {
  font-size: 16px;
  color: #f39c12;
  font-weight: 600;
}

.price-amount {
  font-size: 32px;
  font-weight: 700;
  color: #f39c12;
}

.price-period {
  font-size: 14px;
  color: #909399;
  transition: color 0.2s ease;
}

.vip-upgrade-dialog.dark .price-period {
  color: #6b7280;
}

.original-price {
  font-size: 12px;
  color: #909399;
  text-decoration: line-through;
  margin-top: 5px;
  transition: color 0.2s ease;
}

.vip-upgrade-dialog.dark .original-price {
  color: #6b7280;
}

.plan-features {
  margin-bottom: 20px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
  transition: color 0.2s ease;
}

.vip-upgrade-dialog.dark .feature-item {
  color: #d1d5db;
}

.feature-icon {
  color: #67c23a;
  font-size: 16px;
}

.plan-action {
  text-align: center;
}

.selected-btn {
  background: linear-gradient(45deg, #67c23a, #85ce61);
  border-color: #67c23a;
}

.payment-methods {
  margin-bottom: 25px;
}

.payment-options {
  display: flex;
  gap: 20px;
}

.payment-option {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  flex: 1;
  transition: all 0.2s ease;
}

.vip-upgrade-dialog.dark .payment-option {
  border-color: #334155;
}

.vip-upgrade-dialog.dark :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

.payment-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.vip-upgrade-dialog.dark .payment-info span {
  color: #f1f5f9;
}

.payment-icon {
  width: 24px;
  height: 24px;
}

.order-summary {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  transition: background-color 0.2s ease;
}

.vip-upgrade-dialog.dark .order-summary {
  background: #0f172a;
  border: 1px solid #334155;
}

.summary-content {
  margin-top: 15px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  transition: color 0.2s ease;
}

.vip-upgrade-dialog.dark .summary-row {
  color: #f1f5f9;
}

.discount-row {
  color: #909399;
}

.vip-upgrade-dialog.dark .discount-row {
  color: #6b7280;
}

.discount-amount {
  color: #f39c12;
}

.total-row {
  border-top: 1px solid #e4e7ed;
  padding-top: 10px;
  margin-top: 15px;
  font-size: 16px;
  font-weight: 600;
  transition: border-color 0.2s ease;
}

.vip-upgrade-dialog.dark .total-row {
  border-top-color: #334155;
}

.total-amount {
  color: #f39c12;
  font-size: 18px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pay-button {
  background: linear-gradient(45deg, #f39c12, #e67e22);
  border: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .plans-grid {
    grid-template-columns: 1fr;
  }
  
  .payment-options {
    flex-direction: column;
  }
}
</style>